from django.db import models
from django.utils import timezone


class Game(models.Model):
    """游戏房间"""
    STATUS_CHOICES = [
        ('waiting', '等待中'),
        ('playing', '进行中'),
        ('finished', '已结束')
    ]
    
    player1 = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='games_as_player1', verbose_name="玩家1")
    player2 = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='games_as_player2', null=True, blank=True, verbose_name="玩家2")
    player1_deck = models.ForeignKey('decks.Deck', on_delete=models.CASCADE, related_name='games_as_player1_deck', verbose_name="玩家1卡组")
    player2_deck = models.ForeignKey('decks.Deck', on_delete=models.CASCADE, related_name='games_as_player2_deck', null=True, blank=True, verbose_name="玩家2卡组")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='waiting', verbose_name="游戏状态")
    current_turn = models.IntegerField(default=1, verbose_name="当前回合")
    max_rounds = models.IntegerField(default=5, verbose_name="最大回合数")
    winner = models.ForeignKey('accounts.User', on_delete=models.CASCADE, null=True, blank=True, related_name='won_games', verbose_name="获胜者")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    finished_at = models.DateTimeField(null=True, blank=True, verbose_name="结束时间")
    
    class Meta:
        verbose_name = "游戏"
        verbose_name_plural = "游戏"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"游戏 {self.id} - {self.player1.nickname} vs {self.player2.nickname if self.player2 else '等待中'}"
    
    @property
    def is_full(self):
        """游戏是否已满员"""
        return self.player2 is not None
    
    @property
    def current_player(self):
        """当前回合的玩家"""
        # 如果是AI游戏，始终返回player1
        if self.player2 is None and self.player2_deck is not None:
            return self.player1
        # 普通游戏：奇数回合player1，偶数回合player2
        return self.player1 if self.current_turn % 2 == 1 else self.player2


class GameRound(models.Model):
    """游戏回合"""
    game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='rounds', verbose_name="游戏")
    round_number = models.IntegerField(verbose_name="回合数")
    player1_card = models.ForeignKey('cards.Card', on_delete=models.CASCADE, related_name='rounds_as_player1_card', null=True, blank=True, verbose_name="玩家1出牌")
    player2_card = models.ForeignKey('cards.Card', on_delete=models.CASCADE, related_name='rounds_as_player2_card', null=True, blank=True, verbose_name="玩家2出牌")
    winner = models.ForeignKey('accounts.User', on_delete=models.CASCADE, null=True, blank=True, verbose_name="回合获胜者")
    is_finished = models.BooleanField(default=False, verbose_name="回合是否结束")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "游戏回合"
        verbose_name_plural = "游戏回合"
        ordering = ['round_number']
        unique_together = ['game', 'round_number']
    
    def __str__(self):
        return f"游戏 {self.game.id} - 第 {self.round_number} 回合"


class PlayerAction(models.Model):
    """玩家行动"""
    ACTION_CHOICES = [
        ('play_card', '出牌'),
        ('end_turn', '结束回合'),
    ]
    
    game = models.ForeignKey(Game, on_delete=models.CASCADE, verbose_name="游戏")
    round = models.ForeignKey(GameRound, on_delete=models.CASCADE, related_name='actions', verbose_name="回合")
    player = models.ForeignKey('accounts.User', on_delete=models.CASCADE, null=True, blank=True, verbose_name="玩家")
    action_type = models.CharField(max_length=20, choices=ACTION_CHOICES, verbose_name="行动类型")
    card = models.ForeignKey('cards.Card', on_delete=models.CASCADE, null=True, blank=True, verbose_name="出的卡牌")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="行动时间")
    
    class Meta:
        verbose_name = "玩家行动"
        verbose_name_plural = "玩家行动"
        ordering = ['-created_at']
    
    def __str__(self):
        player_name = self.player.nickname if self.player else "AI"
        return f"{player_name} - {self.get_action_type_display()}"
